package com.geek.water.service.impl;
import com.geek.water.exception.HealthException;
import com.geek.water.service.FileStrategyService;
import com.geek.water.utils.QiniuUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import com.qiniu.storage.Configuration;

import java.util.UUID;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/7/28
 */
@Service("qiniu")
public class QiniuFileStrategy implements FileStrategyService {

    private final QiniuUtils qiniuUtils;
    private Auth auth;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    public QiniuFileStrategy(QiniuUtils qiniuUtils){
        this.qiniuUtils = qiniuUtils;
    }

    @PostConstruct
    public void init() {
        try {
            //鉴权
            this.auth = Auth.create(qiniuUtils.getAccessKey(), qiniuUtils.getSecretKey());
            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            this.uploadManager = new UploadManager(cfg);
            this.bucketManager = new BucketManager(auth, cfg);
            System.out.println("七牛云初始化成功");
        } catch (Exception e) {
            System.err.println("七牛云初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //上传文件
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                System.err.println("文件为空");
                return null;
            }

            String oldName = file.getOriginalFilename();
            if (StringUtils.hasLength(oldName) && oldName.lastIndexOf(".") > 0) {
                String fileName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
                System.out.println("生成的文件名: " + fileName);

                //文件上传
                String token = auth.uploadToken(qiniuUtils.getBucket());
                String key = fileName;

                System.out.println("开始上传到七牛云...");
                //上传
                Response response = uploadManager.put(file.getInputStream(), key, token, null, null);

                if (response.isOK()) {
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    //返回存储在七牛云上的外链地址
                    String finalUrl = qiniuUtils.getHostName() + "/" + putRet.key;
                    System.out.println("上传成功，URL: " + finalUrl);
                    return finalUrl;
                } else {
                    System.err.println("七牛云上传失败，状态码: " + response.statusCode);
                    System.err.println("错误信息: " + response.bodyString());
                    return null;
                }
            } else {
                System.err.println("文件名格式不正确: " + oldName);
                return null;
            }
        } catch (QiniuException ex) {
            System.err.println("七牛云上传异常: " + ex.getMessage());
            ex.printStackTrace();
            return null;
        } catch (Exception ex) {
            System.err.println("文件上传异常: " + ex.getMessage());
            ex.printStackTrace();
            return null;
        }
    }

    //删除文件
    @Override
    public boolean deleteFile(String url) {
        try {
            String fileName = url.replaceAll(qiniuUtils.getHostName() + "/", "");
            System.out.println("要删除的文件名: " + fileName);

            if (StringUtils.hasLength(fileName)) {
                Response response = bucketManager.delete(qiniuUtils.getBucket(), fileName);
                if (response.statusCode == 200) {
                    System.out.println("文件删除成功");
                    return true;
                } else {
                    System.err.println("文件删除失败，状态码: " + response.statusCode);
                    return false;
                }
            } else {
                System.err.println("文件名为空");
                return false;
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println("七牛云删除异常: " + ex.getMessage());
            ex.printStackTrace();
            throw new HealthException("文件删除失败: " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("文件删除异常: " + ex.getMessage());
            ex.printStackTrace();
            return false;
        }
    }
}